package com.bob.web.common.advice;

import com.bob.web.common.constant.CodeConstant;
import com.bob.web.common.constant.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 名称: BaseGolbalBodyReponseAdvice<br>
 * 描述:<br>
 * 类型: JAVA<br>
 * 最近修改时间:2017/7/7 16:43<br>
 *
 * @author BoYangsh
 * @version [版本号, V1.0]
 * @since 2017/7/7 16:43
 */
@ControllerAdvice(basePackages = "com.bob.web.controller")
public class BaseGlobalReponseBodyAdvice implements ResponseBodyAdvice<Object> {

	//这个方法表示对于哪些请求要执行beforeBodyWrite，返回true执行，返回false不执行
	@Override
	public boolean supports(MethodParameter methodParameter, Class aClass) {
		return true;
	}

	//对于返回的对象如果不是最终对象ResponseResult，则选包装一下
	@Override
	public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,
			Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
		if(!(o instanceof ResponseResult)) {
			ResponseResult responseResult = new ResponseResult(CodeConstant.SUCCESS, o);
			return responseResult;
		}
		return o;
	}
}
